package com.hitqz.robot.biz.flow.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 重定向
 *
 * @author wengyongxin
 * @date 2023/11/15 23:53
 **/
@RestController
public class RedirectController {

    /**
     * 如果把React嵌入到springboot，则使用这个进行重定向
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/prod/**", method = RequestMethod.GET)
    public void redirectToBackendGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String originalUrl = request.getRequestURL().toString(); // 获取原始请求的 URL
        String queryString = request.getQueryString(); // 获取原始请求的查询参数
        String backendUrl = originalUrl.replace("/prod", "/flow/drawer");
        if (queryString != null) {
            backendUrl += "?" + queryString; // 将查询参数追加到重定向的 URL
        }
        response.sendRedirect(backendUrl);
    }

    @RequestMapping(value = "/prod/**", method = RequestMethod.DELETE)
    public void redirectToBackendDelete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String backendUrl = request.getRequestURL().toString().replace("/prod", "/flow/drawer");
        response.sendRedirect(backendUrl);
    }

    @RequestMapping(value = "/prod/**", method = RequestMethod.POST)
    public void redirectToBackendPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String backendUrl = request.getRequestURL().toString().replace("/prod", "/flow/drawer");

        // 复制原始请求的输入流数据
        InputStream requestBody = request.getInputStream();
        byte[] requestBodyBytes = requestBody.readAllBytes();

        // 发送 POST 请求到目标 URL
        HttpURLConnection connection = (HttpURLConnection) new URL(backendUrl).openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", request.getContentType());
        connection.setDoOutput(true);
        connection.getOutputStream().write(requestBodyBytes);

        // 将目标 URL 的响应数据写入原始请求的响应中
        response.setStatus(connection.getResponseCode());
        response.setContentType(connection.getContentType());
        InputStream responseStream = connection.getInputStream();
        byte[] responseBytes = responseStream.readAllBytes();
        response.getOutputStream().write(responseBytes);

        connection.disconnect();
    }

}

